import { reactive } from 'vue';

interface ConfirmOptions {
  title?: string;
  message?: string;
  type?: 'warning' | 'error' | 'info' | 'success';
  confirmText?: string;
  cancelText?: string;
}

interface ConfirmItem extends ConfirmOptions {
  id: string;
  resolve: (value: boolean) => void;
  loading: boolean;
}

class ConfirmManager {
  private items = reactive<ConfirmItem[]>([]);
  private idCounter = 0;

  /**
   * 显示确认对话框
   */
  confirm(options: ConfirmOptions = {}): Promise<boolean> {
    const id = `confirm_${++this.idCounter}`;

    return new Promise((resolve) => {
      const item: ConfirmItem = {
        id,
        title: '确认',
        message: '您确定要执行此操作吗？',
        type: 'warning',
        confirmText: '确定',
        cancelText: '取消',
        ...options,
        resolve,
        loading: false
      };

      this.items.push(item);
    });
  }

  /**
   * 确认操作
   */
  handleConfirm(id: string) {
    const item = this.items.find(item => item.id === id);
    if (item) {
      item.resolve(true);
      this.remove(id);
    }
  }

  /**
   * 取消操作
   */
  handleCancel(id: string) {
    const item = this.items.find(item => item.id === id);
    if (item) {
      item.resolve(false);
      this.remove(id);
    }
  }

  /**
   * 设置加载状态
   */
  setLoading(id: string, loading: boolean) {
    const item = this.items.find(item => item.id === id);
    if (item) {
      item.loading = loading;
    }
  }

  /**
   * 移除确认对话框
   */
  remove(id: string) {
    const index = this.items.findIndex(item => item.id === id);
    if (index > -1) {
      this.items.splice(index, 1);
    }
  }

  /**
   * 获取所有确认对话框
   */
  getItems() {
    return this.items;
  }

  /**
   * 清空所有确认对话框
   */
  clear() {
    this.items.forEach(item => item.resolve(false));
    this.items.splice(0);
  }
}

// 创建全局实例
export const confirmManager = new ConfirmManager();

// 全局确认方法
export const $baseConfirm = (message: string, type: ConfirmOptions['type'] = 'warning', title?: string): Promise<boolean> => {
  return confirmManager.confirm({
    message,
    type,
    title: title || ("提示"),
    confirmText: '确定',
    cancelText: '取消'
  });
};

// 快捷方法
export const $confirmDelete = (message: string, title: string = '删除确认'): Promise<boolean> => {
  return confirmManager.confirm({
    message,
    type: 'error',
    title,
    confirmText: '删除',
    cancelText: '取消'
  });
};

export const $confirmWarning = (message: string, title: string = '警告'): Promise<boolean> => {
  return confirmManager.confirm({
    message,
    type: 'warning',
    title,
    confirmText: '确定',
    cancelText: '取消'
  });
};

export const $confirmInfo = (message: string, title: string = '提示'): Promise<boolean> => {
  return confirmManager.confirm({
    message,
    type: 'info',
    title,
    confirmText: '确定',
    cancelText: '取消'
  });
}; 